﻿/* ==============================================================================
*
*   Copyright (c) 2010, Pierre Favier
*   All rights reserved.
*
*   NTasking is free software: you can redistribute it and/or modify it
*   under the terms of the GNU General Public License as published by the
*   Free Software Foundation.
*
*   Redistribution and use in source and binary forms, with or without
*   modification, are permitted provided that the following conditions
*   are met:
*
*   -   Redistributions of source code must retain the above copyright notice,
*       this list of conditions and the following disclaimer.
*
*   -   Redistributions in binary form must reproduce the above
*       copyright notice, this list of conditions and the following
*       disclaimer in the documentation and/or other materials
*       provided with the distribution.
*
*   THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
*   WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
*   OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
*   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
*   BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
*   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
*   TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
*   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
*   ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
*   TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
*   THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
*   SUCH DAMAGE.
*
* ============================================================================== */

using System;
using System.Collections.Generic;
using System.Linq;
using NTasking.Internals;

namespace NTasking
{

    /// <summary>
    /// Represents the result of an asynchronous method call
    /// </summary>
    public class Future
    {

        /// <summary>
        /// Waits until all the calls have been finished or cancelled.
        /// </summary>
        /// <param name="calls">The calls for which result's to wait for.</param>
        public static void WaitAll(IEnumerable<Future> calls)
        {
            Future[] futures = calls.ToArray();

            if (futures.Length == 0)
                return;

            ThreadWrapper current = ThreadWrapper.CurrentThread;
            int count = 0;

            lock (futures[0]._call.CallLock.Locked())
            {
                foreach (Future f in calls)
                {
                    if (current != f._call.Thread)
                        throw new InvalidOperationException();

                    if (!f._call.Finished)
                        count += 1;
                }

                while (count > 0)
                {
                    futures[0]._call.CallLock.WaitLock();
                    count -= 1;
                }
            }
        }


        /// <summary>
        /// Waits until one of the calls have been finished or cancelled.
        /// </summary>
        /// <param name="calls">The calls for which result's to wait for.</param>
        /// <returns>An object representing the result of the call which has been finished</returns>
        public static Future WaitAny(IEnumerable<Future> calls)
        {
            Future[] futures = calls.ToArray();

            if (futures.Length == 0)
                return null;

            ThreadWrapper current = ThreadWrapper.CurrentThread;

            lock (futures[0]._call.CallLock.Locked())
            {
                foreach (Future f in calls)
                {
                    if (current != f._call.Thread)
                        throw new InvalidOperationException();

                    if (f._call.Finished)
                        return f;
                }

                futures[0]._call.CallLock.WaitLock();

                foreach (Future f in calls)
                {
                    if (f._call.Finished)
                        return f;
                }

                return null;
            }
        }


        private readonly MethodCall _call;


        /// <summary>
        /// Initializes a new instance of the <see cref="Future"/> class.
        /// </summary>
        /// <param name="call">The call of which this instance represents the result.</param>
        internal Future(MethodCall call)
        {
            _call = call;
        }


        /// <summary>
        /// Determines whether this instance is finished or cancelled.
        /// </summary>
        /// <returns>
        /// 	<c>true</c> if this instance is done; otherwise, <c>false</c>.
        /// </returns>
        public bool IsDone()
        {
            return _call.Finished;
        }


        /// <summary>
        /// Determines whether this instance is cancelled.
        /// </summary>
        /// <returns>
        /// 	<c>true</c> if this instance is cancelled; otherwise, <c>false</c>.
        /// </returns>
        public bool IsCancelled()
        {
            return _call.Finished && !_call.Context.ResultIsSet;
        }


        /// <summary>
        /// Waits until this instance is finished or cancelled.
        /// </summary>
        public void Wait()
        {
            if (ThreadWrapper.CurrentThread != _call.Thread)
                throw new InvalidOperationException();

            lock (_call.CallLock.Locked())
            {
                while (!_call.Finished)
                    _call.CallLock.WaitLock();
            }
        }


        /// <summary>
        /// Cancels the call of which this instance represents the result.
        /// </summary>
        public void Cancel()
        {
            lock (_call.CallLock.Locked())
            {
                _call.Target.Owner.Cancel(_call, false);
            }
        }


        /// <summary>
        /// Wait until the call is finished or cancelled and check the result of the call; an exception
        /// might be thrown if the call threw an exception or if the call was cancelled.
        /// </summary>
        public void CheckResult()
        {
            Wait();
            _call.Context.CheckResult();
        }

    }


    /// <summary>
    /// Represents the result of an asynchronous method call of a given return type.
    /// </summary>
    /// <typeparam name="RetT">The type of the call's result.</typeparam>
    public class Future<RetT> : Future
    {

        private readonly CallContext<RetT> _context;


        /// <summary>
        /// Initializes a new instance of the <see cref="Future&lt;RetT&gt;"/> class.
        /// </summary>
        /// <param name="call">The call of which this instance represents the result.</param>
        internal Future(MethodCall<RetT> call)
            : base(call)
        {
            _context = call.Context;
        }


        /// <summary>
        /// Wait until the call is finished or cancelled and return the result of the call; an exception
        /// might be thrown if the call threw an exception or if the call was cancelled.
        /// </summary>
        /// <returns>The call's result</returns>
        public RetT Result()
        {
            Wait();
            return _context.Result;
        }

    }

}
